package com.muqi.app.network.http;

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.muqi.app.afinalcache.ACache;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.student.R;

public class AsyncCacheHttpForGet {
	private static AsyncHttpClient client = new AsyncHttpClient();
	private static AsyncCacheHttpForGet utils = null;
	private static ACache mCache = null;
	private static Context mContext;
	
	private AsyncCacheHttpForGet() {
		client.setTimeout(5000);
	}
	
	public static void cancelRequest(Context mContext){
		if(client!=null)
		client.cancelRequests(mContext, true);
	}

	public static AsyncCacheHttpForGet getInstance(Context context) {
		mContext = context.getApplicationContext();
		if (utils == null) {
			synchronized (AsyncCacheHttpForGet.class) {
				if (utils == null) {
					utils = new AsyncCacheHttpForGet();
					mCache = ACache.get(context.getApplicationContext());
				}
			}
		}
		return utils;
	}
	
	private static String getAbsoluteUrl(String relativeUrl) {
		return NetWorkApi.SERVER_IP + relativeUrl;
	}
	
	public interface LoadOverListener {
		void onOverResult(String request, String result);
	}
	
	public static void getCacheHttp(final String urlString, final LoadOverListener mListener) {
		if(NetWorkUtils.isNetworkAvailable(mContext)){
			Log.e("===", getAbsoluteUrl(urlString)+"请求路径");
			client.get(getAbsoluteUrl(urlString), new BaseJsonHttpResponseHandler<JSONObject>() {

				@Override
				public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, JSONObject arg4) {
					ShowToast.showShort(mContext, R.string.sever_break);
					if(mListener!=null) 
						mListener.onOverResult(urlString, "");
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, String result, JSONObject arg3) {
					
					if(mListener!=null) 
						mListener.onOverResult(urlString, result);
					if(mCache!=null) 
						mCache.put(urlString, result, ACache.TIME_DAY*3);
					Log.e("===", result+"请求结果");
				}

				@Override
				protected JSONObject parseResponse(String arg0, boolean arg1)
						throws Throwable {
					Log.e("===", "解析失败");
					return null;
				}
			});
		}else{
			String cacheJson = mCache.getAsString(urlString);
			if(TextUtils.isEmpty(cacheJson)){
				ShowToast.showShort(mContext, R.string.net_break);
				if(mListener!=null) 
					mListener.onOverResult(urlString, "");
			}else{
				if(mListener!=null) 
					mListener.onOverResult(urlString, cacheJson);
			}
		}
	}
}
